package com.dctp.ems.controller;

import com.alibaba.fastjson.JSON;
import com.dctp.common.cache.UserCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.core.RedisManager;
import com.dctp.common.utils.CollectUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.dctp.common.vo.RedisKey;
import com.dctp.ems.utils.OrderAggregator;
import com.dctp.ems.vo.AggregatedResult;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Path("/monitor")
public class MonitorController extends BaseController {

    public void userStat() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);

        // 查询参数
        Long userId = getParaToLong("user_id");
        String symbol = getPara("symbol");
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");


        Integer status = getParaToInt("status",1);

        // 构建 where 子句
        StringBuilder where = new StringBuilder(" WHERE status = ? ");
        List<Object> params = new ArrayList<>();
        params.add(status);

        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }

        String roleKey = getPara("roleKey");
        Long roleUserId = getParaToLong("roleUserId");
        if (StringUtil.isNotEmpty(roleKey) && null != roleUserId) {
            where.append(" AND ").append(roleKey).append(" = ?");
            params.add(roleUserId);
        }

        if (StringUtil.isNotEmpty(symbol)) {
            where.append(" AND symbol = ?");
            params.add(symbol);
        }

        Long contractId = getParaToLong("contract_id");
        if (null != contractId) {
            where.append(" AND contract_id = ?");
            params.add(contractId);
        }
        if (StringUtil.isNotEmpty(startTime)) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }

        // 分组统计 SQL，加上分组的开始/结束时间
        String select = "SELECT user_id, " +
                "SUM(quantity) AS total_quantity, " +
                "IFNULL(SUM(realized_pnl),0) AS total_realized_pnl, " +
                "SUM(open_service_fee + IFNULL(close_service_fee,0)) AS total_service_fee, " +
                "MIN(create_time) AS start_time, MAX(close_time) AS end_time ";

        String from = "FROM dctp_order " + where + " GROUP BY user_id ORDER BY end_time DESC ";
        var pageData = Db.paginate(page, pageSize, select, from, params.toArray());

        List<Long> userIdList = new ArrayList<>();
        if (CollectUtil.isNotEmpty(pageData.getList())) {
            for (Record r : pageData.getList()) {
                Long uid = r.getLong("user_id");
                userIdList.add(uid);
                Record user = UserCache.getBasic(uid);
                if (null != user) {
                    r.set("user",UserCache.getShowInfo(uid));
                    String key = getGroupByIdKey();
                    Long orgId = user.getLong(key);
                    if (null != orgId) {
                        Record showInfo = UserCache.getShowInfo(orgId);
                        r.set("orgInfo", showInfo);
                    }
                }
                List<Record> symbolStatList = Db.find(
                        "SELECT symbol, direction, " +
                                "SUM(quantity) AS total_quantity, " +
                                "SUM(realized_pnl) AS total_realized_pnl, " +
                                "SUM(open_service_fee + close_service_fee) AS total_service_fee " +
                                "FROM dctp_order " +
                                "WHERE user_id = ? AND status = ? " +
                                "GROUP BY symbol, direction",
                        uid, status );
                List<AggregatedResult> aggregatedResults = OrderAggregator.aggregateToList(symbolStatList);
                List<Map<String, Object>> symbolStatMapList = aggregatedResults.stream().map(ar -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("symbol", ar.symbol);
                    map.put("totalQuantity", ar.totalQuantity);
                    map.put("totalPnl", ar.totalPnl);
                    map.put("totalFee", ar.totalFee);

                    map.put("longQuantity", ar.longQuantity);
                    map.put("longPnl", ar.longPnl);
                    map.put("longFee", ar.longFee);

                    map.put("shortQuantity", ar.shortQuantity);
                    map.put("shortPnl", ar.shortPnl);
                    map.put("shortFee", ar.shortFee);

                    return map;
                }).toList();
                r.set("symbolStatList", symbolStatMapList);
            }
        }

        if (CollectUtil.isNotEmpty(userIdList)) {
            Map<String, Object> payload = new HashMap<>();
            payload.put("adminId",getRequestUser().getLong("id"));
            payload.put("type", "2"); // 监控
            payload.put("userIds", userIdList); // List<Long>，会被 JSON 自动序列化为数组
            RedisManager.getInstance().publish(
                    RedisKey.PUB_SUB_ADMIN_ORDER,
                    JSON.toJSONString(payload)
            );
        }
        renderJson(JsonResult.successWithData(
                new PageResult<>(pageData.getList(), pageData.getTotalRow(), pageSize, page)
        ));
    }
}
